package com.example.jenkins.controller;

import com.example.jenkins.dto.ResultMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
public class DemoController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${upload.location-path}")
    private String localPath;
    @RequestMapping("/test")
    public ResultMode<String> test(){
        return new ResultMode<>(0, "成功","锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦。");
    }

    @PostMapping(path = "/upload")
    public ResultMode<HashMap> upload(@RequestParam("key") String appKey,
                                     @RequestPart("file")MultipartFile file){

        log.info("========>");
        log.info("key:"+appKey);
        log.info("file:"+file.getOriginalFilename());
        log.info("<========");
        File outFile = new File(localPath, file.getOriginalFilename());
        if (outFile.exists()){
            outFile.delete();
        }
        try {
            outFile.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            InputStream inputStream = file.getInputStream();
            byte[] buff = new byte[1024];
            int len;
            while (true){
                len = inputStream.read(buff);
                if (len < 0) break;
                fileOutputStream.write(buff,0,len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMode<>(-1, "服务器错误",null);
        }
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("filename", file.getOriginalFilename());
        dataMap.put("filesize", file.getSize());
        dataMap.put("key", appKey);
        return new ResultMode<>(0, "上传成功",dataMap);
    }
}
